import 'dart:convert';
import 'dart:io';
import 'package:explore/provider/person_info.dart';
import 'package:fluent_ui/fluent_ui.dart' as fluent;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _Home();
}

class _Home extends State<Home> {
  XFile? imgPath;
  void updateImagePath(var newImage) {
    setState(() {
      imgPath = newImage;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('首页'),
        ),
        body: Container(
            padding: const EdgeInsets.only(top: 90),
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('image/homeBackground.jpg'),
                fit: BoxFit.cover, // 图片如何适应容器
              ),
            ),
            child: Column(
              children: [
                PhotoAlbum(imgPath: imgPath, updateImagePath: updateImagePath),
                UploadButton(imgPath: imgPath, updateImagePath: updateImagePath)
              ],
            )));
  }
}

// ignore: must_be_immutable
class PhotoAlbum extends StatefulWidget {
  late var imgPath;
  var updateImagePath;

  PhotoAlbum({required this.imgPath, this.updateImagePath}) : super();
  @override
  State<StatefulWidget> createState() => _Upload();
}

class _Upload extends State<PhotoAlbum> {
  void openGallery() async {
    final ImagePicker picker = ImagePicker();
    var image = await picker.pickImage(source: ImageSource.gallery);
    widget.updateImagePath(image);
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: 250,
        height: 250,
        child: Container(
          color: const Color.fromARGB(159, 124, 115, 115),
          child: IconButton(
              icon: widget.imgPath != null
                  ? Image.file(
                      File(widget.imgPath?.path),
                      width: 250,
                      height: 250,
                      fit: BoxFit.cover,
                    )
                  : Image.asset(
                      'image/uploadImage.png',
                    ),
              onPressed: openGallery),
        ));
  }
}

// ignore: must_be_immutable
class UploadButton extends StatefulWidget {
  var imgPath;
  var updateImagePath;

  UploadButton({super.key, required this.imgPath, this.updateImagePath});
  @override
  State<StatefulWidget> createState() => _UploadButton();
}

class _UploadButton extends State<UploadButton> {
  var boolean = false;
  void uploadImage(PersonInfo person) async {
    if (widget.imgPath == null) {
      Fluttertoast.showToast(msg: '请上传图片');
      return;
    }
    setState(() {
      boolean = true;
    });
    File imageFile = File(widget.imgPath?.path);
    Uint8List imageBytes = await imageFile.readAsBytes();
    Uint8List uint8list = Uint8List.fromList(imageBytes);
    DateTime now = DateTime.now();
    int timestamp = now.millisecondsSinceEpoch;
    Map info = {
      "alliance": person.alliance,
      "name": person.name,
      "act": person.act,
      "keyword": person.keyword,
      "count": person.count
    };
    final url = Uri.parse('http://127.0.0.1:5000/upload');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body =
        jsonEncode({'timestamp': timestamp, 'image': uint8list, "info": info});

    final request = http.Request('get', url);
    request.headers.addAll(headers);
    request.body = body;
    final response = await request.send();
    final responseBody = await response.stream.bytesToString();
    var jsonData = jsonDecode(responseBody);
    if (response.statusCode == 200) {
      if (jsonData["code"] == "510") {
        Fluttertoast.showToast(msg: '照片审核失败，请联系管理');
        setState(() {
          boolean = false;
        });
        return;
      }

      widget.updateImagePath(null);
      Fluttertoast.showToast(msg: '上传成功');
      setState(() {
        boolean = false;
      });
    } else {
      Fluttertoast.showToast(msg: '上传失败');
      setState(() {
        boolean = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<PersonInfo>(builder: (ctx, person, child) {
      return Container(
          margin: const EdgeInsets.only(top: 60),
          child: TextButton(
            style: TextButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.blue,
                minimumSize: const Size(250, 50),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30))),
            onPressed: () => uploadImage(person),
            child: (boolean == false)
                ? const Text(
                    "点击上传",
                    style: TextStyle(fontSize: 30),
                  )
                : const fluent.ProgressRing(
                    backgroundColor: Colors.blue,
                    activeColor: Colors.white,
                  ),
          ));
    });
  }
}
